#!/usr/bin/env bash
set -e

if [ "$EUID" -ne 0 ]; then
    echo "error: this script must be run as root" >&2
    exit 1
fi

RELEASE="$1"
ARCH=amd64 # TODO: maybe i686 too

case "$RELEASE" in
    jammy)
        extra_packages=(python3-pip)
        ;;
    *)
        echo "error: unsupported target release: $RELEASE" >&2
        exit 1
        ;;
esac

THIS_DIR="$(dirname "$(readlink -f "$0")")"

set -x

CONTAINER_NAME=zulip-install-$RELEASE-base

if ! lxc-info -n "$CONTAINER_NAME" >/dev/null 2>&1; then
    lxc-create -n "$CONTAINER_NAME" -t download -- -d ubuntu -r "$RELEASE" -a "$ARCH"
fi

lxc-start -n "$CONTAINER_NAME"
"$THIS_DIR"/lxc-wait -n "$CONTAINER_NAME"

run() {
    lxc-attach --clear-env -n "$CONTAINER_NAME" -- "$@"
}

run passwd -d root

run apt-get update

run apt-get dist-upgrade -y

# As an optimization, we install a bunch of packages the installer
# would install for itself.
run apt-get install -y --no-install-recommends \
    xvfb parallel unzip zip jq python3-pip curl eatmydata \
    git crudini openssl ssl-cert \
    build-essential python3-dev \
    memcached redis-server \
    hunspell-en-us supervisor libssl-dev puppet \
    gettext libffi-dev libfreetype6-dev zlib1g-dev libjpeg-dev \
    libldap2-dev \
    libxml2-dev libxslt1-dev libpq-dev \
    virtualenv \
    "${extra_packages[@]}"

run ln -sf /usr/share/zoneinfo/Etc/UTC /etc/localtime
run locale-gen C.UTF-8 || true
echo "LC_ALL=C.UTF-8" | run tee /etc/default/locale

# TODO: on failure, either stop or print message
lxc-stop -n "$CONTAINER_NAME"
